<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="考试名称" prop="examName">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考试名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试状态" prop="examStatus">
        <!-- （0待发布 1已发布 2进行中 3已结束） -->
        <el-select v-model="queryParams.examStatus" placeholder="请选择考试状态" clearable>
          <el-option label="待发布" value="0"></el-option>
          <el-option label="已发布" value="1"></el-option>
          <el-option label="进行中" value="2"></el-option>
          <el-option label="已结束" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['examation:examation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['examation:examation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['examation:examation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['examation:examation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试名称" align="center" prop="examName" width="200"/>
      <el-table-column label="考试描述" align="center" prop="examDescription" width="300"/>
      <el-table-column label="考试时长" align="center" prop="examDuration" />
      <el-table-column label="总分" align="center" prop="totalScore" />
      <el-table-column label="及格分数" align="center" prop="passScore" />
      <el-table-column label="考试状态" align="center" prop="examStatus">
        <template slot-scope="scope">
          <el-tag :type="getExamStatusType(scope.row.examStatus)">
            {{ getExamStatusText(scope.row.examStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['examation:examation:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['examation:examation:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['examation:examation:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['examation:examation:query']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <!-- <el-dropdown-item command="examSettings" icon="el-icon-setting">考场设置</el-dropdown-item> -->
              <el-dropdown-item command="examStatistics" icon="el-icon-pie-chart">报名统计</el-dropdown-item>
              <el-dropdown-item command="classRelation" icon="el-icon-connection">关联班次</el-dropdown-item>
              <el-dropdown-item command="examSchedule" icon="el-icon-time">考试时间</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="form.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="考试描述" prop="examDescription">
          <el-input v-model="form.examDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="考试时长" prop="examDuration">
          <el-input v-model="form.examDuration" placeholder="请输入考试时长" />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input v-model="form.totalScore" placeholder="请输入总分" />
        </el-form-item>
        <el-form-item label="及格分数" prop="passScore">
          <el-input v-model="form.passScore" placeholder="请输入及格分数" />
        </el-form-item>
        <el-form-item label="考试状态" prop="examStatus">
          <el-select v-model="form.examStatus" placeholder="请选择考试状态" clearable>
            <el-option label="待发布" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="进行中" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看考试详情对话框 -->
    <el-dialog title="考试详情" :visible.sync="viewOpen" width="70%" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="考试名称">
          {{ viewData.examName }}
        </el-descriptions-item>
        <el-descriptions-item label="考试时长">
          {{ viewData.examDuration }} 分钟
        </el-descriptions-item>
        <el-descriptions-item label="总分">
          {{ viewData.totalScore }}
        </el-descriptions-item>
        <el-descriptions-item label="及格分数">
          {{ viewData.passScore }}
        </el-descriptions-item>
        <el-descriptions-item label="考试状态">
          <el-tag :type="getExamStatusType(viewData.examStatus)">
            {{ getExamStatusText(viewData.examStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ viewData.createTime ? parseTime(viewData.createTime) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="考试描述" :span="2">
          {{ viewData.examDescription }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ viewData.remark }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 考场设置对话框 -->
    <el-dialog :title="'考场设置 - ' + currentExam.examName" :visible.sync="venueSettingsOpen" width="60%" append-to-body>
      <div class="mb8">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleVenueAdd"
        >新增考场</el-button>
      </div>
      
      <el-table v-loading="venueLoading" :data="venueList" style="width: 100%">
        <el-table-column label="考场名称" align="center" prop="venueName" />
        <el-table-column label="考场地址" align="center" prop="venueAddress" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180"/>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180"/>
        <el-table-column label="考场容量" align="center" prop="capacity" width="80" />
        <el-table-column label="已报名人数" align="center" prop="registeredCount" width="100" />
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleVenueUpdate(scope.row)"
              style="color: #409eff;"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleVenueDelete(scope.row)"
              style="color: #f56c6c;"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="venueSettingsOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增考场对话框 -->
    <el-dialog :title="venueTitle" :visible.sync="venueAddOpen" width="600px" append-to-body>
      <el-form ref="venueForm" :model="venueForm" :rules="venueRules" label-width="100px">
        <el-form-item label="考场名称" prop="venueName">
          <el-input v-model="venueForm.venueName" placeholder="请输入考场名称" />
        </el-form-item>
        <el-form-item label="考场地址" prop="venueAddress">
          <el-input v-model="venueForm.venueAddress" type="textarea" placeholder="请输入考场地址" />
        </el-form-item>
        <el-form-item label="考试日期" prop="examDate">
          <el-date-picker
            v-model="venueForm.examDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择考试日期"
            style="width: 100%;"
            clearable
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="venueForm.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始时间"
            style="width: 100%;"
            :default-time="['00:00:00']"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="venueForm.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束时间"
            style="width: 100%;"
            :default-time="['00:00:00']"
            clearable
          />
        </el-form-item>
        <el-form-item label="考场容量" prop="capacity">
          <el-input-number v-model="venueForm.capacity" :min="1" placeholder="请输入考场容量" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="venueForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitVenueForm">确 定</el-button>
        <el-button @click="cancelVenueForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报名统计对话框 -->
    <el-dialog :title="'报名统计 - ' + currentExam.examName" :visible.sync="statisticsOpen" width="80%" append-to-body>
      <div class="mb8">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExportRegistrationList"
        >导出报名人员名单</el-button>
      </div>
      <el-table v-loading="statisticsLoading" :data="examScheduleList" style="width: 100%">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="考试开始时间" align="center" prop="startTime" >
          <template slot-scope="scope">
            <span>{{ scope.row.startTime ? parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考试结束时间" align="center" prop="endTime" >
          <template slot-scope="scope">
            <span>{{ scope.row.endTime ? parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="时间段状态" align="center" prop="scheduleStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="getScheduleStatusType(scope.row.scheduleStatus)">
              {{ getScheduleStatusText(scope.row.scheduleStatus) }}
            </el-tag>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="是否启用" align="center" prop="isEnabled" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isEnabled === '1' ? 'success' : 'danger'">
              {{ scope.row.isEnabled === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="报名人数" align="center" prop="registrationCount">
          <template slot-scope="scope">
            <span style="color: #409eff; font-weight: bold;">{{ scope.row.registrationCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center"  >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewScheduleRegistrations(scope.row)"
              style="color: #409eff;"
            >查看报名详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="statisticsOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 时段报名详情对话框 -->
    <el-dialog :title="'时段报名详情'" :visible.sync="scheduleRegistrationOpen" width="80%" append-to-body>
      <div style="margin-bottom: 16px;">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="考试时间">
            {{ currentSchedule.startTime ? parseTime(currentSchedule.startTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }} 至 {{ currentSchedule.endTime ? parseTime(currentSchedule.endTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="报名人数">
            <span style="color: #409eff; font-weight: bold;">{{ currentSchedule.registrationCount || 0 }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <el-table v-loading="scheduleRegistrationLoading" :data="scheduleRegistrationUsersList" style="width: 100%">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="用户姓名" align="center" prop="userName" />
        <el-table-column label="用户账号" align="center" prop="nickName" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="考场名称" align="center" prop="venueName" />
        <el-table-column label="报名时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报名状态" align="center" prop="registrationStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.registrationStatus === '1' ? 'success' : 'info'">
              {{ scope.row.registrationStatus === '1' ? '已报名' : '待确认' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="scheduleRegistrationTotal > 0"
        :total="scheduleRegistrationTotal"
        :page.sync="scheduleRegistrationQuery.pageNum"
        :limit.sync="scheduleRegistrationQuery.pageSize"
        @pagination="handleScheduleRegistrationPagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="scheduleRegistrationOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 关联班次对话框 -->
    <el-dialog :title="'关联班次 - ' + currentExam.examName" :visible.sync="classRelationOpen" width="80%" append-to-body>
      <div style="margin-bottom: 16px;">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          size="small" 
          @click="handleAddClassRelation"
        >新增关联班次</el-button>
      </div>
      
      <el-table v-loading="classLoading" :data="relatedClassList" style="width: 100%">
        <el-table-column label="班次名称" align="center" prop="className" width="200" />
        <el-table-column label="班次编码" align="center" prop="classCode" width="150" />
        <el-table-column label="班次描述" align="center" prop="classDescription" show-overflow-tooltip />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.startTime ? parseTime(scope.row.startTime, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.endTime ? parseTime(scope.row.endTime, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="班次状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="getClassStatusType(scope.row.status)">
              {{ getClassStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="学员数量" align="center" prop="studentCount" width="100" />
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              style="color: #f56c6c;"
              @click="handleRemoveClassRelation(scope.row)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="relatedClassTotal > 0"
        :total="relatedClassTotal"
        :page.sync="relatedClassQuery.pageNum"
        :limit.sync="relatedClassQuery.pageSize"
        @pagination="handleRelatedClassPagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="classRelationOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 考试时间管理对话框 -->
    <el-dialog :title="'考试时间管理 - ' + currentExam.examName" :visible.sync="examScheduleOpen" width="80%" append-to-body>
      <div class="mb8">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleScheduleAdd"
        >新增考试时间</el-button>
      </div>
      
      <el-table v-loading="scheduleLoading" :data="scheduleList" style="width: 100%">
        <el-table-column label="考试开始时间" align="center" prop="startTime" >
          <template slot-scope="scope">
            <span>{{ scope.row.startTime ? parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考试结束时间" align="center" prop="endTime" >
          <template slot-scope="scope">
            <span>{{ scope.row.endTime ? parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间段状态" align="center" prop="scheduleStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="getScheduleStatusType(scope.row.scheduleStatus)">
              {{ getScheduleStatusText(scope.row.scheduleStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center" prop="isEnabled" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isEnabled === '1' ? 'success' : 'danger'">
              {{ scope.row.isEnabled === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleScheduleUpdate(scope.row)"
              style="color: #409eff;"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleScheduleDelete(scope.row)"
              style="color: #f56c6c;"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="examScheduleOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/修改考试时间对话框 -->
    <el-dialog :title="scheduleTitle" :visible.sync="scheduleAddOpen" width="600px" append-to-body>
      <el-form ref="scheduleForm" :model="scheduleForm" :rules="scheduleRules" label-width="120px">
        <el-form-item label="考试开始时间" prop="startTime">
          <el-date-picker
            v-model="scheduleForm.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择考试开始时间"
            style="width: 100%;"
            clearable
          />
        </el-form-item>
        <el-form-item label="考试结束时间" prop="endTime">
          <el-date-picker
            v-model="scheduleForm.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择考试结束时间"
            style="width: 100%;"
            clearable
          />
        </el-form-item>
        <el-form-item label="时间段状态" prop="scheduleStatus">
          <el-select v-model="scheduleForm.scheduleStatus" placeholder="请选择时间段状态" clearable>
            <el-option label="未开始" value="0"></el-option>
            <el-option label="报名中" value="1"></el-option>
            <el-option label="考试中" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
            <el-option label="已取消" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-radio-group v-model="scheduleForm.isEnabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="scheduleForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitScheduleForm">确 定</el-button>
        <el-button @click="cancelScheduleForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增班次关联对话框 -->
    <el-dialog title="选择要关联的班次" :visible.sync="addClassRelationOpen" width="70%" append-to-body>
      <el-alert
        title="提示：已关联的班次不会在列表中显示"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 16px;"
      ></el-alert>
      <el-form :model="classSearchParams" ref="classSearchForm" size="small" :inline="true" style="margin-bottom: 16px;">
        <el-form-item label="班次名称" prop="className">
          <el-input 
            v-model="classSearchParams.className" 
            placeholder="请输入班次名称" 
            clearable 
            @keyup.enter.native="searchAvailableClasses"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchAvailableClasses">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetClassSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table 
        v-loading="availableClassListLoading" 
        :data="availableClassList" 
        @selection-change="handleClassSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="班次名称" align="center" prop="className" width="200" />
        <el-table-column label="班次编码" align="center" prop="classCode" width="150" />
        <el-table-column label="班次描述" align="center" prop="classDescription" show-overflow-tooltip />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.startTime ? parseTime(scope.row.startTime, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.endTime ? parseTime(scope.row.endTime, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="班次状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="getClassStatusType(scope.row.status)">
              {{ getClassStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="学员数量" align="center" prop="studentCount" width="100" />
      </el-table>
      
      <pagination
        v-show="availableClassTotal > 0"
        :total="availableClassTotal"
        :page.sync="availableClassSearchQuery.pageNum"
        :limit.sync="availableClassSearchQuery.pageSize"
        @pagination="handleAvailableClassPagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button 
          type="primary" 
          @click="submitClassRelation" 
          :disabled="selectedClasses.length === 0 || submittingClassRelation"
          :loading="submittingClassRelation"
        >
          {{ submittingClassRelation ? '关联中...' : `确定关联 (${selectedClasses.length})` }}
        </el-button>
        <el-button @click="cancelAddClassRelation" :disabled="submittingClassRelation">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExamation, getExamation, delExamation, addExamation, updateExamation, getExamClasses, addExamClass, removeExamClass } from "@/api/examation/examation";
import { listExamVenue, addExamVenue, delExamVenue, updateExamVenue } from "@/api/examation/examVenue";
import { getRegistrationUsers, getRegistrationUsersBySchedule } from "@/api/examation/examRegistration";
import { listClass, listAllClass } from "@/api/course/class";
import { listExamSchedule, addExamSchedule, updateExamSchedule, delExamSchedule, listByExamIdWithCount } from "@/api/examation/examSchedule";

export default {
  name: "Examation",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试信息表格数据
      examationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看对话框控制变量
      viewOpen: false,
      // 查看数据
      viewData: {},
      // 考场设置对话框控制变量
      venueSettingsOpen: false,
      // 考场新增对话框控制变量
      venueAddOpen: false,
      // 考场对话框标题
      venueTitle: "",
      // 当前选中的考试信息
      currentExam: {},
      // 考场列表
      venueList: [],
      // 考场列表加载状态
      venueLoading: false,
      // 考场表单数据
      venueForm: {},
      // 考场表单校验规则
      venueRules: {
        venueName: [
          { required: true, message: "考场名称不能为空", trigger: "blur" }
        ],
        venueAddress: [
          { required: true, message: "考场地址不能为空", trigger: "blur" }
        ],
        examDate: [
          { required: true, message: "考试日期不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        capacity: [
          { required: true, message: "考场容量不能为空", trigger: "blur" }
        ]
      },
      // 报名统计对话框控制变量
      statisticsOpen: false,
      // 考试时段列表数据（用于报名统计）
      examScheduleList: [],
      // 报名统计加载状态
      statisticsLoading: false,
      // 时段报名详情对话框控制变量
      scheduleRegistrationOpen: false,
      // 当前选中的时段信息
      currentSchedule: {},
      // 时段报名用户列表
      scheduleRegistrationUsersList: [],
      // 时段报名详情加载状态
      scheduleRegistrationLoading: false,
      // 时段报名详情总数
      scheduleRegistrationTotal: 0,
      // 时段报名详情查询参数
      scheduleRegistrationQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 关联班次对话框控制变量
      classRelationOpen: false,
      // 已关联班次列表
      relatedClassList: [],
      // 已关联班次列表加载状态
      classLoading: false,
      // 已关联班次总数
      relatedClassTotal: 0,
      // 已关联班次查询参数
      relatedClassQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 新增班次关联对话框控制变量
      addClassRelationOpen: false,
      // 可选班次列表数据
      availableClassList: [],
      // 可选班次列表加载状态
      availableClassListLoading: false,
      // 可选班次列表总数
      availableClassTotal: 0,
      // 可选班次搜索查询参数
      availableClassSearchQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 班次搜索参数
      classSearchParams: {
        className: null,
        classCode: null
      },
      // 选中的班次列表
      selectedClasses: [],
      // 提交班次关联状态
      submittingClassRelation: false,
      // 考试时间管理对话框控制变量
      examScheduleOpen: false,
      // 考试时间列表
      scheduleList: [],
      // 考试时间列表加载状态
      scheduleLoading: false,
      // 考试时间新增对话框控制变量
      scheduleAddOpen: false,
      // 考试时间对话框标题
      scheduleTitle: "",
      // 考试时间表单数据
      scheduleForm: {},
      // 考试时间表单校验规则
      scheduleRules: {
        startTime: [
          { required: true, message: "考试开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "考试结束时间不能为空", trigger: "blur" }
        ],
        scheduleStatus: [
          { required: true, message: "时间段状态不能为空", trigger: "blur" }
        ],
        isEnabled: [
          { required: true, message: "是否启用不能为空", trigger: "blur" }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examName: null,
        examDescription: null,
        examDuration: null,
        totalScore: null,
        passScore: null,
        examStatus: null,
        remark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "考试ID不能为空", trigger: "blur" }
        ],
        examName: [
          { required: true, message: "考试名称不能为空", trigger: "blur" }
        ],
        examDescription: [
          { required: true, message: "考试描述不能为空", trigger: "blur" }
        ],
        examDuration: [
          { required: true, message: "考试时长不能为空", trigger: "blur" }
        ],
        totalScore: [
          { required: true, message: "总分不能为空", trigger: "blur" }
        ],
        passScore: [
          { required: true, message: "及格分数不能为空", trigger: "blur" }
        ],
        examStatus: [
          { required: true, message: "考试状态不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "备注不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询考试信息列表 */
    getList() {
      this.loading = true;
      listExamation(this.queryParams).then(response => {
        this.examationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        examName: null,
        examDescription: null,
        examDuration: null,
        totalScore: null,
        passScore: null,
        examStatus:null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExamation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考试信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExamation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试信息编号为"' + ids + '"的数据项？').then(function() {
        return delExamation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('examation/examation/export', {
        ...this.queryParams
      }, `examation_${new Date().getTime()}.xlsx`)
    },
    /** 查看按钮操作 */
    handleView(row) {
      const id = row.id;
      getExamation(id).then(response => {
        this.viewData = response.data;
        this.viewOpen = true;
      });
    },
    /** 更多操作触发 */
    handleCommand(command, row) {
      switch (command) {
        case "examSettings":
          this.handleExamSettings(row);
          break;
        case "examStatistics":
          this.handleExamStatistics(row);
          break;
        case "classRelation":
          this.handleClassRelation(row);
          break;
        case "examSchedule":
          this.handleExamSchedule(row);
          break;
        default:
          break;
      }
    },
    /** 考场设置操作 */
    handleExamSettings(row) {
      this.currentExam = row;
      this.venueSettingsOpen = true;
      this.getVenueList();
    },
    /** 统计分析操作 */
    handleExamStatistics(row) {
      this.currentExam = row;
      this.statisticsOpen = true;
      this.getExamScheduleListWithCount();
    },
    /** 获取考试时段列表（带报名人数统计） */
    getExamScheduleListWithCount() {
      this.statisticsLoading = true;
      this.examScheduleList = [];
      listByExamIdWithCount(this.currentExam.id).then(response => {
        this.examScheduleList = response.data || [];
        this.statisticsLoading = false;
      }).catch(() => {
        this.statisticsLoading = false;
      });
    },
    /** 导出报名人员名单 */
    handleExportRegistrationList() {
      if (!this.currentExam || !this.currentExam.id) {
        this.$modal.msgWarning("请先选择考试");
        return;
      }
      this.download('business/examSchedule/exportRegistrationList', {
        examId: this.currentExam.id
      }, `exam_registration_${new Date().getTime()}.xlsx`)
    },
    /** 查看时段报名详情 */
    handleViewScheduleRegistrations(schedule) {
      this.currentSchedule = schedule;
      this.scheduleRegistrationOpen = true;
      this.resetScheduleRegistrationQuery();
      this.getScheduleRegistrationUsers();
    },
    /** 重置时段报名详情查询参数 */
    resetScheduleRegistrationQuery() {
      this.scheduleRegistrationQuery = {
        pageNum: 1,
        pageSize: 10
      };
    },
    /** 获取时段报名用户列表 */
    getScheduleRegistrationUsers() {
      this.scheduleRegistrationLoading = true;
      this.scheduleRegistrationUsersList = [];
      getRegistrationUsersBySchedule(this.currentExam.id, this.currentSchedule.id, this.scheduleRegistrationQuery).then(response => {
        this.scheduleRegistrationUsersList = response.rows || response.data || [];
        this.scheduleRegistrationTotal = response.total || 0;
        this.scheduleRegistrationLoading = false;
      }).catch(() => {
        this.scheduleRegistrationLoading = false;
      });
    },
    /** 时段报名详情分页 */
    handleScheduleRegistrationPagination(val) {
      this.scheduleRegistrationQuery.pageNum = val.page;
      this.scheduleRegistrationQuery.pageSize = val.limit;
      this.getScheduleRegistrationUsers();
    },
    /** 获取考场列表 */
    getVenueList() {
      this.venueLoading = true;
      const queryParams = {
        pageNum: 1,
        pageSize: 1000, // 获取所有考场
        examId: this.currentExam.id
      };
      listExamVenue(queryParams).then(response => {
        this.venueList = response.rows;
        this.venueLoading = false;
      }).catch(() => {
        this.venueLoading = false;
      });
    },
    /** 考场新增按钮操作 */
    handleVenueAdd() {
      this.resetVenueForm();
      this.venueForm.examId = this.currentExam.id;
      this.venueTitle = "新增考场";
      this.venueAddOpen = true;
    },
    /** 考场删除按钮操作 */
    handleVenueDelete(venue) {
      this.$modal.confirm('是否确认删除考场"' + venue.venueName + '"？').then(function() {
        return delExamVenue(venue.id);
      }).then(() => {
        this.getVenueList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 考场修改按钮操作 */
    handleVenueUpdate(venue) {
      this.resetVenueForm();
      this.venueForm = { ...venue }; // 复制考场信息到表单
      this.venueTitle = "修改考场";
      this.venueAddOpen = true;
    },
    /** 重置考场表单 */
    resetVenueForm() {
      this.venueForm = {
        id: null,
        examId: null,
        venueName: null,
        venueAddress: null,
        examDate: null,
        startTime: null,
        endTime: null,
        capacity: 30,
        registeredCount: 0,
        venueStatus: "0",
        remark: null
      };
      this.resetForm("venueForm");
    },
    /** 考场表单取消按钮 */
    cancelVenueForm() {
      this.venueAddOpen = false;
      this.resetVenueForm();
    },
    /** 考场表单提交按钮 */
    submitVenueForm() {
      this.$refs["venueForm"].validate(valid => {
        if (valid) {
          if (this.venueForm.id) { // 如果是修改
            updateExamVenue(this.venueForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.venueAddOpen = false;
              this.getVenueList();
            });
          } else { // 如果是新增
            addExamVenue(this.venueForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.venueAddOpen = false;
              this.getVenueList();
            });
          }
        }
      });
    },
    /** 获取考试状态类型 */
    getExamStatusType(status) {
      const statusMap = {
        '0': 'info',    // 待发布
        '1': 'success', // 已发布
        '2': 'warning', // 进行中
        '3': 'danger'   // 已结束
      };
      return statusMap[status] || 'info';
    },
    /** 获取考试状态文本 */
    getExamStatusText(status) {
      const statusMap = {
        '0': '待发布',
        '1': '已发布',
        '2': '进行中',
        '3': '已结束'
      };
      return statusMap[status] || '未知';
    },
    /** 关联班次操作 */
    handleClassRelation(row) {
      this.currentExam = row;
      this.classRelationOpen = true;
      this.resetRelatedClassQuery();
      this.getRelatedClassList();
    },
    /** 获取已关联班次列表 */
    getRelatedClassList() {
      this.classLoading = true;
      getExamClasses(this.currentExam.id, this.relatedClassQuery).then(response => {
        this.relatedClassList = response.rows || response.data || [];
        this.relatedClassTotal = response.total || this.relatedClassList.length;
        this.classLoading = false;
      }).catch(() => {
        this.classLoading = false;
      });
    },
    /** 重置已关联班次查询参数 */
    resetRelatedClassQuery() {
      this.relatedClassQuery = {
        pageNum: 1,
        pageSize: 10
      };
    },
    /** 已关联班次列表分页 */
    handleRelatedClassPagination(val) {
      this.relatedClassQuery.pageNum = val.page;
      this.relatedClassQuery.pageSize = val.limit;
      this.getRelatedClassList();
    },
    /** 处理新增班次关联 */
    handleAddClassRelation() {
      this.resetClassSearch();
      this.getAvailableClassList();
      this.addClassRelationOpen = true;
    },
    /** 重置班次搜索 */
    resetClassSearch() {
      this.classSearchParams = {
        className: null,
        classCode: null
      };
      this.availableClassSearchQuery = {
        pageNum: 1,
        pageSize: 10
      };
      this.selectedClasses = [];
      this.submittingClassRelation = false;
    },
    /** 搜索可选班次 */
    searchAvailableClasses() {
      this.availableClassSearchQuery.pageNum = 1;
      this.getAvailableClassList();
    },
    /** 获取可选班次列表 */
    getAvailableClassList() {
      this.availableClassListLoading = true;
      const queryParams = {
        ...this.availableClassSearchQuery,
        ...this.classSearchParams
      };
      listAllClass(queryParams).then(response => {
        let classList = response.rows || response.data || [];
        
        // 过滤掉已经关联的班次
        const relatedClassIds = this.relatedClassList.map(classItem => classItem.id);
        classList = classList.filter(classItem => !relatedClassIds.includes(classItem.id));
        
        this.availableClassList = classList;
        this.availableClassTotal = classList.length; // 注意：这里使用过滤后的长度
        this.availableClassListLoading = false;
      }).catch(() => {
        this.availableClassListLoading = false;
      });
    },
    /** 可选班次列表分页 */
    handleAvailableClassPagination(val) {
      this.availableClassSearchQuery.pageNum = val.page;
      this.availableClassSearchQuery.pageSize = val.limit;
      this.getAvailableClassList();
    },
    /** 班次选择变化 */
    handleClassSelectionChange(selection) {
      this.selectedClasses = selection;
    },
    /** 提交班次关联 */
    submitClassRelation() {
      if (this.selectedClasses.length === 0) {
        this.$modal.msgWarning("请选择要关联的班次");
        return;
      }
      
      this.submittingClassRelation = true;
      
      // 提取选中班次的ID列表
      const classIds = this.selectedClasses.map(classItem => classItem.id);
      
      // 调用后端关联接口
      addExamClass(this.currentExam.id, classIds).then(response => {
        this.$modal.msgSuccess(`成功关联 ${this.selectedClasses.length} 个班次`);
        this.addClassRelationOpen = false;
        this.getRelatedClassList();
        this.resetClassSearch();
        this.submittingClassRelation = false;
      }).catch(() => {
        this.submittingClassRelation = false;
      });
    },
    /** 取消新增班次关联 */
    cancelAddClassRelation() {
      this.addClassRelationOpen = false;
      this.resetClassSearch();
    },
    /** 移除班次关联 */
    handleRemoveClassRelation(row) {
      this.$modal.confirm('是否确认移除班次"' + row.className + '"的关联？').then(() => {
        // 调用后端移除关联接口
        removeExamClass(this.currentExam.id, row.classId).then(response => {
          this.$modal.msgSuccess("移除班次关联成功");
          this.getRelatedClassList();
        }).catch(() => {});
      }).catch(() => {});
    },
    /** 获取班次状态类型 */
    getClassStatusType(status) {
      const statusMap = {
        '0': 'info',     // 招生
        '1': 'warning',  // 考试
        '2': 'success'   // 结束
      };
      return statusMap[status] || 'info';
    },
    /** 获取班次状态文本 */
    getClassStatusText(status) {
      const statusMap = {
        '0': '招生',
        '1': '考试',
        '2': '结束'
      };
      return statusMap[status] || '未知';
    },
    /** 考试时间管理操作 */
    handleExamSchedule(row) {
      this.currentExam = row;
      this.examScheduleOpen = true;
      this.getScheduleList();
    },
    /** 获取考试时间列表 */
    getScheduleList() {
      this.scheduleLoading = true;
      const queryParams = {
        pageNum: 1,
        pageSize: 1000, // 获取所有考试时间
        examId: this.currentExam.id
      };
      listExamSchedule(queryParams).then(response => {
        this.scheduleList = response.rows || response.data || [];
        this.scheduleLoading = false;
      }).catch(() => {
        this.scheduleLoading = false;
      });
    },
    /** 考试时间新增按钮操作 */
    handleScheduleAdd() {
      this.resetScheduleForm();
      this.scheduleForm.examId = this.currentExam.id;
      this.scheduleTitle = "新增考试时间";
      this.scheduleAddOpen = true;
    },
    /** 考试时间修改按钮操作 */
    handleScheduleUpdate(schedule) {
      this.resetScheduleForm();
      this.scheduleForm = { ...schedule }; // 复制考试时间信息到表单
      this.scheduleTitle = "修改考试时间";
      this.scheduleAddOpen = true;
    },
    /** 考试时间删除按钮操作 */
    handleScheduleDelete(schedule) {
      this.$modal.confirm('是否确认删除考试时间"' + schedule.scheduleName + '"？').then(function() {
        return delExamSchedule(schedule.id);
      }).then(() => {
        this.getScheduleList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 重置考试时间表单 */
    resetScheduleForm() {
      this.scheduleForm = {
        id: null,
        examId: null,
        scheduleName: null,
        startTime: null,
        endTime: null,
        scheduleStatus: "0",
        isEnabled: "1",
        remark: null
      };
      this.resetForm("scheduleForm");
    },
    /** 考试时间表单取消按钮 */
    cancelScheduleForm() {
      this.scheduleAddOpen = false;
      this.resetScheduleForm();
    },
    /** 考试时间表单提交按钮 */
    submitScheduleForm() {
      this.$refs["scheduleForm"].validate(valid => {
        if (valid) {
          if (this.scheduleForm.id) { // 如果是修改
            updateExamSchedule(this.scheduleForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.scheduleAddOpen = false;
              this.getScheduleList();
            });
          } else { // 如果是新增
            addExamSchedule(this.scheduleForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.scheduleAddOpen = false;
              this.getScheduleList();
            });
          }
        }
      });
    },
    /** 获取时间段状态类型 */
    getScheduleStatusType(status) {
      const statusMap = {
        '0': 'info',     // 未开始
        '1': 'success',  // 报名中
        '2': 'warning',  // 考试中
        '3': 'danger',   // 已结束
        '4': 'danger'    // 已取消
      };
      return statusMap[status] || 'info';
    },
    /** 获取时间段状态文本 */
    getScheduleStatusText(status) {
      const statusMap = {
        '0': '未开始',
        '1': '报名中',
        '2': '考试中',
        '3': '已结束',
        '4': '已取消'
      };
      return statusMap[status] || '未知';
    }
  }
};
</script>
